import random
import uuid

from flask import render_template, request, session, jsonify, make_response, redirect, url_for
from flask_mail import Message

from main import mail
from models import db
from models.index import User
from . import passport_blu


@passport_blu.route('/passport/login', methods=['POST', 'GET'])
def login():
    method = request.method
    if method == 'GET':
        return render_template('./user/login.html')
    else:
        email = request.json.get("email")
        password = request.json.get("password")
        user = db.session.query(User).filter(User.email == email, User.password_hash == password).first()

        if user:
            ret = {
                "errno": 0,
                "errmsg": "登录成功"
            }

            session['user_id'] = user.id
            session['nick_name'] = user.nick_name
            return jsonify(ret)
        else:
            ret = {
                "errno": 2001,
                "errmsg": "邮箱或者密码错误"
            }

            return jsonify(ret)


@passport_blu.route('/passport/reg', methods=['POST', 'GET'])
def reg():
    method = request.method
    if method == 'GET':
        return render_template('./user/reg.html')

    else:
        email = request.json.get("email")
        emailCode = request.json.get("emailCode")
        password = request.json.get("password")
        re_password = request.json.get("re_password")
        nick_name = request.json.get("nick_name")
        imgCode = request.json.get("imgCode")
        #     # 2. 测试数据
        # print(email, password, emailCode, re_password, imgCode)
    # 判断密码是否一样
    if password != re_password:
        ret = {
            "errno": 2000,
            "errmsg": "两次输入的密码不一样"
        }
        return jsonify(ret)
    # 判断邮箱
    if session.get('email_code') != emailCode:
        ret = {
            "errno": 2001,
            "errmsg": "重新输入邮箱验证码"
        }
        return jsonify(ret)
    # 判断图片验证码
    if session.get("image_code").lower() != imgCode.lower():
        ret = {
            "errno": 2002,
            "errmsg": "重新输入验证码"
        }
        return jsonify(ret)
    # 判断邮箱是否注册
    if db.session.query(User).filter(User.email == email).first():
        return jsonify({
            "errno": 2003,
            "errmsg": "已经注册..."
        })

    # 2.2 注册用户
    # 将新用户的数据插入到数据库
    user = User()
    user.nick_name = nick_name
    user.password_hash = password
    user.email = email
    try:
        activekey = str(uuid.uuid1())
        # 去掉里面的-
        activekey = activekey.replace('-', '')

        # 3. 未注册，那么则进行注册
        db.session.add(user)
        db.session.commit()

        # 注册成功之后，立刻认为登录成功，也就说需要进行状态保持
        session['user_id'] = user.id
        session['nick_name'] = nick_name

        ret = {
            "errno": 0,
            "errmsg": "注册成功..."
        }
        return jsonify(ret)
    except Exception as ret:
        db.session.rollback()
        ret = {
            "errno": 1002,
            "errmsg": "注册失败..."
        }

        return jsonify(ret)


@passport_blu.route('/passport/email_code', methods=['POST'])
def email_code():
    email = request.json.get('email')
    msg = Message('你好', sender='z1248849985@163.com', recipients=[email])
    # 这里的sender是发信人，写上你发信人的邮箱。
    # recipients是收信人，用一个列表去表示。
    msg.body = '激活邮件'
    email_code = str(random.randint(100000, 999999))

    msg.html = '亲爱的会员： 您好！您正在注册账号，请在验证码输入框中输入：%s，以完成操作。' % (email_code)
    # 发送
    mail.send(msg)

    session['email_code'] = email_code
    ret = {
        "errno": 0,
        "errmsg": "发送成功..."
    }
    return jsonify(ret)


@passport_blu.route("/passport/image_code")
def image_code():
    # 读取一个图片
    # with open("./yanzhengma.png", "rb") as f:
    #     image = f.read()

    # 真正的生成一张图片数据
    from utils.captcha.captcha import captcha

    # 生成验证码
    # hash值  验证码值  图片内容
    name, text, image = captcha.generate_captcha()

    # print("刚刚生成的验证码：", text)

    # 通过session的方式，缓存刚刚生成的验证码，否则注册时不知道刚刚生成的是多少
    session['image_code'] = text

    # 返回响应内容
    resp = make_response(image)

    # 设置内容类型
    resp.headers['Content-Type'] = 'image/png'

    return resp


@passport_blu.route("/passport/logout")
def logout():
    # 清空登录状态
    session.clear()

    return redirect(url_for('index_blu.index'))
